package com.seabook.happy.website.daos;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.seabook.happy.website.pojos.BlogArticle;
import com.seabook.happy.website.pojos.BlogComment;

public class BlogCommentDao {
	private DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();

	public void saveComment(BlogComment comment, BlogArticle blogArticle) {
		saveComment(comment, blogArticle.getKey());
	}
	
	public void saveComment(BlogComment comment, Key key) {
		Entity entity = new Entity(EntitesKind.BLOG_COMMENT_KIND, key);
		entity.setProperty(BlogComment.CONTENT, comment.getContent());
		entity.setProperty(BlogComment.MODIFIED_DATE, comment.getModifiedDate());
		entity.setProperty(BlogComment.USERNAME, comment.getUsername());
		entity.setProperty(BlogComment.EMAIL, comment.getEmail());
		datastore.put(entity);
	}
	
	public List<BlogComment> findAllRelatedComments(BlogArticle blogArticle) {
		Query query = new Query(EntitesKind.BLOG_COMMENT_KIND);
		query.setAncestor(blogArticle.getKey());
		
		List<Entity> results = datastore.prepare(query).asList(
			    FetchOptions.Builder.withDefaults());
		
		return transferEntity2BlogComment(results);
	}
	
	private List<BlogComment> transferEntity2BlogComment(List<Entity> blogComments) {
		List<BlogComment> comments = new ArrayList<BlogComment>();
		for (Entity entity : blogComments) {
			BlogComment comment = new BlogComment();
			comment.setKey(entity.getKey());
			comment.setContent((Text)entity.getProperty(BlogComment.CONTENT));
			comment.setModifiedDate((Date)entity.getProperty(BlogComment.MODIFIED_DATE));
			comment.setUsername((String)entity.getProperty(BlogComment.USERNAME));
			comment.setEmail((String)entity.getProperty(BlogComment.EMAIL));
			comments.add(comment);
		}
		
		return comments;
	}
	
}
